#include <stdio.h>
#include <stdlib.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include "sio.h"

#define RS _BV(PD4)
#define RW _BV(PD3)
#define E _BV(PD2)
#define DB0 _BV(PB0)
#define DB1 _BV(PB1)
#define DB2 _BV(PB2)
#define DB3 _BV(PB3)
#define DB4 _BV(PB4)
#define DB5 _BV(PB5)
#define DB6 _BV(PB6)
#define DB7 _BV(PB7)

void timer_init(void)
{
	TCCR1B = _BV(CS12);		// set TCNT1 to 1:256 prescaler
}

void pwmRight(unsigned Ton, unsigned period)
{
	OCR2A = period>>1;	// sets OCR2A to period/2
	OCR2B = Ton>>1;		// sets OCR2B to Ton/2

	// Enable TCNT1 with 1:64 prescaler, set up PWM mode
	TCCR2A = _BV(COM2B1) | _BV(WGM20);
	TCCR2B = _BV(WGM22) | _BV(CS21) | _BV(CS20);
}

void char_input(void)
{
	printf("\r\n");
	int c, j = 7, decimal;
	unsigned mask = 0b10000000;

	while(1)
	{
		c = inchar();
		printf("binary: ");
		while(mask > 0)
		{
			printf("%u", (((unsigned)c) & mask)>>j);
			decimal |= (((unsigned)c) & mask);
			mask >>= 1;
			j--;
		}
		mask = 0b10000000;
		j = 7;
		printf(" char: %c decimal: %d\r\n", c, decimal);
		decimal = 0;
	}
}

void OScopeTest(void)
{
  	while (1)
	{
		for(int i = 0; i < 8; i++)
		{
			PORTD ^= _BV(PD6);
			printf("%u", (PIND & _BV(PD2)) >> 2);
			_delay_ms(100);
			printf("%u", (PIND & _BV(PD2)) >> 2);
			_delay_ms(100);
		}
		_delay_ms(1000);
  	}
}

void LED_brightness(void)
{
	int c;
	unsigned delay = 100;
	while(1)
	{
		c = input();
		if(c == '-')
			delay = 15000;
		else if(c == '=')
			delay = 100;
		printf("\r\ndelay %u", delay);
		PORTC ^= _BV(PC6);
		_delay_us(delay);
		PORTC ^= _BV(PC6);
		_delay_us(delay);
	}
}

void LCD_Enable(void)
{
	PORTB |= DB3 | DB2;
	PORTD &= ~RS & ~RW;
	_delay_us(1);
	PORTD |= E;
}
